import 'dart:convert';

import 'package:base_flutter/base_flutter.dart' as b;
import 'package:dio/dio.dart';
import 'package:flustars_flutter3/flustars_flutter3.dart';
import 'package:flutter/material.dart';
import 'package:flutter_cupertino_date_picker_fork/flutter_cupertino_date_picker_fork.dart';
import 'package:ls_work/a_elder/models/waiting_right_entity.dart';
import 'package:ls_work/a_yyt/models/pending_entity.dart';
import 'package:ls_work/mvp/svp_progress.dart';
import 'package:ls_work/net/HttpUtil.dart';
import 'package:ls_work/net/net.dart';
import 'package:ls_work/res/colors.dart';
import 'package:ls_work/res/gaps.dart';
import 'package:ls_work/res/styles.dart';
import 'package:ls_work/util/toast.dart';

import '../../widgets/out_line_button.dart';





class HomePendingServiceBatchExecutionpage extends StatefulWidget {
  final Map<String, List<WaitingRighInfo>>? map;
  final VoidCallback? callBack;
  HomePendingServiceBatchExecutionpage({Key? key, this.map, this.callBack});
  @override
  _HomePendingServiceBatchExecutionpageState createState() =>
      _HomePendingServiceBatchExecutionpageState();
}

class _HomePendingServiceBatchExecutionpageState
    extends State<HomePendingServiceBatchExecutionpage>
    with SingleTickerProviderStateMixin, AutomaticKeepAliveClientMixin {
  PageController _pageController = PageController(initialPage: 0);
  TabController? _tabController;

  List<String> titleList = [];
  List<List<WaitingRighInfo>> dataList = [];

  @override
  bool get wantKeepAlive => true;

  @override
  void initState() {
    super.initState();
    (widget.map??{}).forEach((key, value) {
      titleList.add(key);
      dataList.add(value);
    });
    _tabController = new TabController(vsync: this, length: (widget.map??{}).length);
  }

  @override
  void dispose() {
    _tabController?.dispose();
    _pageController.dispose();
    super.dispose();
  }

  _onPageChange(int index) {
    _tabController?.animateTo(index);
  }

  _executeServicePlanRecordBatch() {
    List<WaitingRighInfo> selectedDataList = [];
    for (var itemList in dataList) {
      for (var item in itemList) {
        if (item.isSelected==true) {
          selectedDataList.add(item);
        }
      }
    }
    if (selectedDataList.length <= 0) {
      Toast.show("请选择至少一项服务");
      return;
    }

    List tempList = [];
    for (var item in selectedDataList) {
      Map<String, dynamic> map = {};
      map["id"] = item.bizId;
      map["executeStatus"] = 0;
      map["finishTime"] =
          DateUtil.formatDate(item.dateTime, format: DateFormats.full);
      map["remark"] = item.itemRemark;
      if ((item.bizParams?.result??[]).length > 0) {
        var temp = [];
        for (var i = 0; i < (item.bizParams?.result??[]).length; i++) {
          temp.add({
            'value': item.bizParams!.result![i].textEditingController!.text ?? "",
            'rangeTo': item.bizParams!.result![i].rangeTo ?? "",
            'rangeFrom': item.bizParams!.result![i].rangeFrom ?? "",
            'subItem': item.bizParams!.result![i].subItem,
          });
        }
        map['result'] = jsonEncode(temp);
      }
      tempList.add(map);
    }
    SVProgressHUD page = SVProgressHUD(context);
    page.showProgress();
    HttpUtil.instance
        .getDio()
        .post(
          "${HttpApi.executeServicePlanRecordBatch}?jsonStr=${jsonEncode(tempList)}",
        )
        .then((r) {
      page.closeProgress();
      if (r.statusCode == 200) {
        Map<String, dynamic> map = json.decode(r.toString());
        if (map["code"].toString() == "0") {
          Toast.show(map["msg"]);
          if(widget.callBack!=null){
            widget.callBack!();
          }
          Navigator.pop(context);
        } else {
          Toast.show(map["msg"]);
        }
      } else {
        Toast.show(r.statusCode.toString());
      }
    }).catchError((e) {
      page.closeProgress();
      print(e.toString());
      Toast.show(getErrorMessage(e));
    });
  }

  @override
  Widget build(BuildContext context) {
    super.build(context);
    return Scaffold(
      appBar: AppBar(
        title: Text("服务计划"),
        elevation: 0.5,
        actions: [
          TextButton(
            onPressed: _executeServicePlanRecordBatch,
            child: Text("提交"),
          ),
        ],
        bottom: TabBar(
          onTap: (index) {
            if (!mounted) {
              return;
            }
            _pageController.jumpToPage(index);
          },
          isScrollable: true,
          controller: _tabController,
          labelStyle: TextStyle(fontSize: 16, fontWeight: FontWeight.bold),
          indicatorSize: TabBarIndicatorSize.label,
          unselectedLabelColor: Colours.text_gray,
          unselectedLabelStyle: TextStyles.textGray14,
          labelColor: Colours.text_dark,
          indicatorColor: Colours.app_main,
          indicatorPadding: EdgeInsets.only(bottom: 5),
          tabs: titleList.map((e) => Tab(text: e)).toList(),
        ),
      ),
      body: PageView.builder(
        key: const Key('pageView'),
        itemCount: (widget.map??{}).length,
        onPageChanged: _onPageChange,
        controller: _pageController,
        itemBuilder: (BuildContext context, int index) {
          List<WaitingRighInfo> _dataList = dataList[index];
          return PendingServicePage(dataList: _dataList);
        },
      ),
    );
  }
}

class PendingServicePage extends StatefulWidget {
  final List<WaitingRighInfo>? dataList;
  PendingServicePage({Key? key, this.dataList});
  @override
  _PendingServicePageState createState() => _PendingServicePageState();
}

class _PendingServicePageState extends State<PendingServicePage> {
  bool allSelected = false;
  List<WaitingRighInfo> selectedDataList = [];

  @override
  Widget build(BuildContext context) {
    return Container(
      width: ScreenUtil.getScreenW(context),
      height: ScreenUtil.getScreenH(context),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        mainAxisAlignment: MainAxisAlignment.start,
        children: [
          Container(
            margin: EdgeInsets.fromLTRB(15, 8, 15, 8),
            width: 100,
            decoration: BoxDecoration(
              color: Colours.app_main,
              borderRadius: BorderRadius.circular(8),
            ),
            child: Row(
              mainAxisAlignment: MainAxisAlignment.start,
              children: [
                Checkbox(
                  value: allSelected,
                  onChanged: (value) {
                    setState(() {
                      allSelected = value!;
                      for (var item in (widget.dataList??<WaitingRighInfo>[])) {
                        item.isSelected = value;
                        if (value) {
                          selectedDataList.add(item);
                        }
                      }
                      if (!value) {
                        selectedDataList.clear();
                      }
                    });
                  },
                ),
                Text(
                  "全选",
                  style: TextStyle(
                    color: Colors.white,
                    fontSize: 16,
                  ),
                ),
              ],
            ),
          ),
          Expanded(
            child: ListView.separated(
              itemBuilder: (context, index) {
                return Container(
                  padding: EdgeInsets.all(15),
                  child: Column(
                    mainAxisAlignment: MainAxisAlignment.start,
                    crossAxisAlignment: CrossAxisAlignment.start,
                    children: [
                      Row(
                        mainAxisAlignment: MainAxisAlignment.spaceBetween,
                        children: [
                          Checkbox(
                            value: widget.dataList![index].isSelected,
                            onChanged: (value) {
                              setState(() {
                                widget.dataList![index].isSelected = value!;
                                bool temp = true;
                                for (var item in (widget.dataList??<WaitingRighInfo>[])) {
                                  if (item.isSelected == false) {
                                    temp = false;
                                    break;
                                  }
                                }
                                allSelected = temp;
                                if (value) {
                                  selectedDataList.add(widget.dataList![index]);
                                } else {
                                  selectedDataList
                                      .remove(widget.dataList![index]);
                                }
                              });
                            },
                          ),
                          Text(
                            "${widget.dataList![index].bizParams?.elderName??""}",
                            style: TextStyles.textDark16,
                          ),
                          Expanded(child: Gaps.hGap15),
                          OutlineButton(
                            padding: EdgeInsets.fromLTRB(15, 8, 15, 8),
                            child: Row(
                              children: [
                                Icon(
                                  Icons.access_time,
                                  color: Colours.text_gray,
                                ),
                                Gaps.hGap10,
                                Text(
                                    "${DateUtil.formatDate(widget.dataList![index].dateTime, format: DateFormats.full)}"),
                              ],
                            ),
                            onPressed: () {
                              _showDateTimePicker(index);
                            },
                          )
                        ],
                      ),
                      Gaps.vGap12,
                      (widget.dataList![index].bizParams?.result??[]).length > 0
                          ? Column(
                              children: widget.dataList![index].bizParams!.result!
                                  .map((e) {
                                return _serviceItem(
                                  widget.dataList![index],
                                  e,
                                  e.textEditingController!,
                                );
                              }).toList(),
                            )
                          : Gaps.empty,
                     ( widget.dataList![index].bizParams?.result??[]).length > 0
                          ? Gaps.vGap12
                          : SizedBox(),
                      Container(
                        color: Colors.white,
                        alignment: Alignment.topLeft,
                        child: TextField(
                          maxLines: 2,
                          autofocus: false,
                          decoration: InputDecoration(
                            hintText: "请输入备注",
                            fillColor: Colours.bg_color,
                            filled: true,
                            border: InputBorder.none,
                          ),
                          onChanged: (value) {
                            widget.dataList![index].itemRemark = value;
                          },
                        ),
                      ),
                    ],
                  ),
                );
              },
              separatorBuilder: (context, index) => Gaps.line,
              itemCount: (widget.dataList??[]).length,
            ),
          )
        ],
      ),
    );
  }

  Widget _serviceItem(
      WaitingRighInfo model, PendingInfo e, TextEditingController controller) {
    return Column(
      mainAxisAlignment: MainAxisAlignment.start,
      crossAxisAlignment: CrossAxisAlignment.start,
      children: <Widget>[
        Container(
          padding: EdgeInsets.fromLTRB(0, 0, 12, 0),
          margin: EdgeInsets.only(left: 15),
          width: ScreenUtil.getScreenW(context),
          decoration: BoxDecoration(
            border: Border(
              bottom: Divider.createBorderSide(context,
                  color: Colours.line, width: 1),
            ),
          ),
          child: Row(
            mainAxisAlignment: MainAxisAlignment.start,
            children: <Widget>[
              Text(
                TextUtil.isEmpty(e.property)
                    ? '${e.subItem}'
                    : '${e.subItem}（${e.property}）',
                style: TextStyles.textDark18,
              ),
              SizedBox(
                width: 10,
              ),
              Expanded(
                child: TextField(
                  keyboardType: TextInputType.number,
                  textAlign: TextAlign.center,
                  style: TextStyles.textGray18,
                  controller: controller,
                  autofocus: false,
                  decoration: InputDecoration(
                    hintText: "输入${e.subItem}数值",
                    hintStyle: TextStyles.textGray18,
                    fillColor: Colors.white,
                    filled: true,
                    border: InputBorder.none,
                  ),
                ),
              ),
              Text(
                '${model.resultUnit ?? ''}',
                style: TextStyles.textDark18,
              )
            ],
          ),
        ),
        Container(
          padding: EdgeInsets.fromLTRB(15, 5, 15, 0),
          child: Text(
            '正常范围：${e.rangeFrom != "null" ? e.rangeFrom : ""} ~ ${e.rangeTo != "null" ? e.rangeTo : ""}',
            style: TextStyles.textGray14,
          ),
        ),
        Gaps.vGap10,
      ],
    );
  }

  ///调起时间选择器
  _showDateTimePicker(int index) {
    DatePicker.showDatePicker(
      context,
      minDateTime: DateTime.parse("1999-01-01"),
      maxDateTime: DateTime.parse("2099-01-01"),
      initialDateTime: widget.dataList![index].dateTime,
      dateFormat: DateFormats.full,
      locale: DateTimePickerLocale.zh_cn,
      pickerTheme: DateTimePickerTheme(
        showTitle: true,
        cancel: Text("取消"),
        confirm: Text('确定'),
      ),
      pickerMode: DateTimePickerMode.time,
      onConfirm: (dateTime, List<int> index2) {
        setState(() {
          widget.dataList![index].dateTime = dateTime;
        });
      },
    );
  }
}
